<template>
  <a-card :bordered="false">
    <h3>广告位管理</h3>
    <MarketingFilter ref="filter" @onAddAd="handleAddOrEditAd" @onSearch="onSearch"></MarketingFilter>
     <a-tabs v-model="activeKey" @change="tabChange">
      <a-tab-pane v-for="item in tabList" :tab="item.name" :key="item.id"></a-tab-pane>
    </a-tabs>
    <s-table ref="table" size="default" bordered :rowKey="record => record.id" :columns="columns" :data="loadData" :pagination="paginationProps" :scroll="{ x: 1300 }" :key="activeKey">
      <span slot="img" slot-scope="text, record">
        <img class="img" :src="record.image" alt="" />
      </span>
      <span slot="weId" slot-scope="text, record">
        {{record.weName}}
      </span>
      <span slot="sort" slot-scope="text, record"> 1 <a-icon type="edit" @click="handleEditSort" /> </span>
      <span slot="sorting" slot-scope="text, record">
        {{record.sorting}} <a-icon type="edit" @click="handleShowSortModal(record.id)" />
      </span>
      <span slot="action" slot-scope="text, record">
        <a @click="handleAddOrEditAd(record.id)">编辑</a>
        <a-divider type="vertical" />
        <template v-if="record.status == '进行中'">
          <a-popconfirm title="确认要下线该广告吗？" ok-text="确定" cancel-text="暂不" @confirm="handleOffline(record.id)">
            <a>下线</a>
          </a-popconfirm>
          <a-divider type="vertical" />
        </template>
        <a-popconfirm title="确认要删除该广告吗？" ok-text="确定" cancel-text="暂不" @confirm="handleAdvertisingDelete(record.id)">
          <a>删除</a>
        </a-popconfirm>
      </span>
    </s-table>
    <a-modal title="编辑排序值" :visible="sortVisible" width="400px" @ok="handleSubmitSort" @cancel="sortVisible = false">
      <a-input-number v-model="sorting" style="width: 100%;" :min="0" :max="999"  placeholder=" 请输入排序值"  />
    </a-modal>
  </a-card>
</template>
<script>
import { cadvertisingPage, advertisingDelete, advertisingAddOrUpdate, advertisingCount, advertisingDownLine } from '@/api/micromall/communityMarketing'
import { STable } from '@/views/box/components'
import MarketingFilter from '../../components/MarketingFilter'

const columns = [
  {
    title: '广告类型',
    width: '200px',
    align: 'center',
    dataIndex: 'advertisingType',
    filterMultiple: false,
    filters: [
      { text: '开屏弹窗', value: '1' },
      { text: '首页瀑布流', value: '2' },
      { text: '首页话题区', value: '3' }
    ]
  },
  {
    title: '广告id',
    width: '200px',
    align: 'center',
    dataIndex: 'id',
  },
  {
    title: '标题/话题',
    width: '180px',
    align: 'center',
    dataIndex: 'title',
  },
  {
    title: '图片',
    width: '100px',
    align: 'center',
    scopedSlots: { customRender: 'img' }
  },
  {
    title: '跳转方式',
    width: '120px',
    align: 'center',
    filterMultiple: false,
    dataIndex: 'jumpWay',
    filters: [
      { text: '小程序路径', value: '1' },
      { text: '自定义链接', value: '2' },
      { text: '视频号', value: '3' },
      { text: '不跳转', value: '4' },
      { text: '话题', value: '5' }
    ]
  },
  {
    title: '落地页',
    width: '420px',
    align: 'center',
    dataIndex: 'landIngPage',
  },
  {
    title: '排序值',
    width: '120px',
    align: 'center',
    // dataIndex: 'sorting',
    scopedSlots: { customRender: 'sorting' }
  },
  {
    title: '状态',
    width: '120px',
    align: 'center',
    dataIndex: 'status',
    filterMultiple: false,
    filters: [
      { text: '未开始', value: '0' },
      { text: '已结束', value: '1' },
      { text: '进行中', value: '2' }
    ]
  },
  {
    title: '投放小程序',
    width: '120px',
    align: 'center',
    dataIndex: 'weId',
    filterMultiple: false,
    scopedSlots: { customRender: 'weId' },
    filters: [
      { text: 'JNBY', value: '2738574294' },
      { text: 'LESS', value: '2822095692' },
      { text: '速写', value: '2504948039' },
      { text: 'jnbybyJNBY', value: '4' },
      { text: '奥莱', value: '11' },
      { text: '江南布衣+', value: '5' },
      { text: '蓬马', value: '6924108367' },
      { text: 'APN', value: '15' },
      { text: 'JNBYHOME', value: '8348044436' }
    ]
  },
  {
    title: '上线时间',
    width: '120px',
    align: 'center',
    dataIndex: 'onlineTime',
    sorter: true
  },
  {
    title: '下线时间',
    width: '120px',
    align: 'center',
    dataIndex: 'offlineTime',
    sorter: true
  },
  {
    title: '操作',
    width: '150px',
    align: 'center',
    fixed: 'right',
    scopedSlots: { customRender: 'action' }
  }
]

const tabList = [
  {
    name: '全部',
    id: ''
  },
  {
    name: '进行中',
    id: '2'
  },
  {
    name: '未开始',
    id: '0'
  },
  {
    name: '已结束',
    id: '1'
  }
]

export default {
  components: {
    MarketingFilter,
    STable
  },
  data() {
    return {
      sort: {},
      filters: {},
      id: '',
      sorting: '',
      sortVisible: false,
      tabList,
      activeKey: tabList[0].id,
      labelCol: {
        xs: { span: 24 },
        sm: { span: 5 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      columns,
      paginationProps: {
        total: 0,
        showTotal: total => `共有 ${total} 条数据`
        // onShowSizeChange: (current, pageSize) => this.changePageSize(current, pageSize)
      },
      queryParam: {},
      // 加载数据方法 必须为 Promise 对象
      loadData: parameter => {
        if (this.requestFlag()) return
       if (parameter.sortOrder) {
          this.sort = {}
          this.sort[parameter.sortField] = parameter.sortOrder == 'descend' ? 0 : 1
        } else {
          delete this.sort[parameter.sortField]
        }
        this.tableFilters(parameter)
        const data = {
          ...this.queryParam,
          current: parameter.pageNo,
          size: parameter.pageSize,
          status: this.activeKey,
          ...this.sort,
          ...this.filters
        }
        return cadvertisingPage(data).then(res => {
          if (res.code === 200) {
            const { records, total, size, current } = res.data
            const data = {
              page: {
                count: total,
                pageNo: current,
                pageSize: size,
                pages: Math.ceil(total / size)
              },
              data: records
            }
            return data
          } else {
            this.$message.error(res.msg || res.message)
            const data = {
              page: {
                count: 0,
                pageNo: 0,
                pages: 0
              },
              data: []
            }
            return data
          }
        })
      }
    }
  },
  created() {
    
  },
  filters: {
  },
  computed: {},
  mounted() {},
  activated() {
    this.getAdvertisingCount()
  },
  watch: {
    $route(to, from) {
      const whiteList = ['/micromall/community/marketingManagement/addOrEditAdvertisement']
      const currentPathBase = '/micromall/community/marketingManagement/advertisementList'
      const currentPath = this.$route.path
      if (this.checkRoute(from.path, whiteList) && to.path.includes(currentPathBase)) {
        this.$refs.table.refresh() // 刷新当前列表（记录上次页码）
      } else {
        if (currentPath.includes(currentPathBase)) {
          if (this.activeKey == tabList[0].id) {
            this.activeKey = tabList[1].id
            this.tabChange(this.activeKey) // 刷新当前页面
          }
          const that = this
          setTimeout(() => {
            that.activeKey = tabList[0].id
            that.tabChange(that.activeKey) // 刷新当前页面
          }, 1)
        }
      }
    }
  },
  methods: {
    requestFlag() {
      const currentPathBase = '/micromall/community/marketingManagement/advertisementList'
      const currentPath = this.$route.path
      if (!currentPath.includes(currentPathBase)) return true
      return false
    },

    // 列表filters
    tableFilters(parameter) {
      console.log(parameter, 'parameter*****************')
      this.columns.filter(e => e.filters).map(e => e.dataIndex).forEach(key => {
          if (parameter[key]) {
            if (parameter[key].length) {
              if (key == 'advertisingType' || key == 'jumpWay') {
                this.filters[key+'Id'] = parameter[key][0]
              } else {
                this.filters[key] = parameter[key][0]
              }  
            } else {
              console.log('ccccc')
              delete this.filters[key]
              delete this.filters[key+'Id']
            }
          }
      })
    },

    // 获取状态数量
    getAdvertisingCount() {
      if (this.requestFlag()) return
      advertisingCount().then(res => {
        if (res.code === 200) {
          const {all, effective, end, notStart} = res.data
          this.tabList[0].name = `全部（${all || 0}）`
          this.tabList[1].name = `进行中（${effective || 0}）`
          this.tabList[2].name = `未开始（${notStart || 0}）`
          this.tabList[3].name = `已结束（${end || 0}）`
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    tabChange(activeKey) {
      this.sort = {}
      this.filters = {}
      this.activeKey = activeKey
      this.$refs.filter.reset()
    },

    // 删除
    handleAdvertisingDelete(id){
      advertisingDelete({id}).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getAdvertisingCount()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

    // 下线
    handleOffline(id) {
      const data = {
        id
        // offlineTime: this.getTime()
      }
      advertisingDownLine(data).then(res => {
        if (res.code === 200) {
          this.$refs.table.refresh()
          this.getAdvertisingCount()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    },

      // 获取当前时间
    getTime() {
      const nowdate = new Date()
      const year = nowdate.getFullYear(),
        month = this.checkTime(nowdate.getMonth() + 1),
        date =  this.checkTime(nowdate.getDate()),
        h =  this.checkTime(nowdate.getHours()),
        m = this.checkTime(nowdate.getMinutes()),
        s =  this.checkTime(nowdate.getSeconds())
      return `${year}-${month}-${date} ${h}:${m}:${s}`
    },

    // 时间补位
    checkTime(i) {
      if (i < 10) {
        i = '0' + i
      }
      return i
    },

    // 新增编辑广告
    handleAddOrEditAd(v) {
      this.$router.push(`/micromall/community/marketingManagement/addOrEditAdvertisement/${v}`)
    },

    // 编辑排序值
    handleEditSort() {
      this.sortVisible = true
    },

    checkRoute(fromPath, routeArr) {
      for (let i = 0; i < routeArr.length; i++) {
        if (fromPath.includes(routeArr[i])) {
          return true
        }
      }
      return false
    },

    //查询
    onSearch(obj) {
      this.queryParam = obj
      this.$refs.table.refresh(true)
    },

    // 打开修改排序值
    handleShowSortModal(id) {
      this.id = id
      this.sortVisible = true
    },

    //修改排序值
    handleSubmitSort() {
      if (!this.sorting) {
        this.$message.error('请输入排序值！')
        return
      }
      this.sortVisible = false
      const data = {
        id: this.id,
        sorting: this.sorting
      }
      advertisingAddOrUpdate(data).then(res => {
        if (res.code === 200) {
          this.sorting = ''
          this.$refs.table.refresh()
        } else {
          this.$message.error(res.msg || res.message)
        }
      })
    }
  }
}
</script>
<style lang="less" scoped>
/deep/ .ant-tabs-bar {
  margin-bottom: 0;
}

.img {
  display: block;
  margin: 0 auto;
  width: 60px;
  height: 60px;
  border: 1px dashed #f5f5f5;
  object-fit: scale-down;
  cursor: pointer;
}

.remarks {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 3;
  word-break: break-all; /* 追加这一行代码 */
  /* autoprefixer: off */
  -webkit-box-orient: vertical;
  /* autoprefixer: on */
}
</style>
